package cn.codepandas.unifiedresponse.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * 注册定制的 responseResultInterceptor，并解决由 String 的 return-type 引起的异常
 *
 * @author Amaris
 * @since 1.0.0
 */
@Configuration
public class MvcConfiguration implements WebMvcConfigurer {

    @Autowired
    private UnifiedResponseHandleInterceptor unifiedResponseHandleInterceptor;

    /**
     * 注册定制的拦截器
     * @param registry InterceptorRegistry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(unifiedResponseHandleInterceptor).addPathPatterns("/**");
    }

    /**
     * 重写转换器以避免字符串作为返回类型无法转换的异常
     * @param converters 官方的转换器
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 把 String 类型的转换器移除，会使用后面的转换器进行转换
        converters.removeIf(httpMessageConverter -> httpMessageConverter.getClass() == StringHttpMessageConverter.class);
    }

}
